<script setup lang="ts">
import { onMounted, ref, nextTick, reactive, h } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElMessageBox } from "element-plus";
import { StatusTag } from "@/components/DynamicTable/components";
import {
  getChildScheduledTaskData,
  deleteChildScheduledTask,
} from "../servers";

const props = defineProps<{
  task: string;
}>();

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// 任务周期映射
const cycleMap = [
  {
    label: "24小时",
    value: "24 hour",
  },
  {
    label: "12小时",
    value: "12 hour",
  },
  {
    label: "6小时",
    value: "6 hour",
  },
  {
    label: "1小时",
    value: "1 hour",
  },
  {
    label: "30分钟",
    value: "30 minute",
  },
  {
    label: "自定义",
    value: "custom",
  },
];

// 任务类型映射
const typeMap = [
  {
    label: "Page Monitoring",
    value: "Page Monitoring",
  },
  {
    label: "Vulnerability Scan",
    value: "Vulnerability Scan",
  },
  {
    label: "Asset Discovery",
    value: "Asset Discovery",
  },
  {
    label: "Port Scan",
    value: "Port Scan",
  },
  {
    label: "Service Identification",
    value: "Service Identification",
  },
];

// 状态映射
const statusMap = [
  {
    label: "启用",
    value: true,
  },
  {
    label: "禁用",
    value: false,
  },
];

const taskList = ref([]);
const loading = ref(false);

// 表单引用
const searchFormRef = ref<DynamicFormInstance>();

const columns = ref<TableColumn[]>([
  {
    label: "序号",
    prop: "index",
    show: true,
    render: (row, column, cellValue, index) => {
      return (pagination.currentPage - 1) * pagination.pageSize + index + 1;
    },
  },
  {
    label: "任务名称",
    prop: "name",
    show: true,
  },
  {
    label: "任务周期",
    prop: "cycle",
    show: true,
    render: (row, column, cellValue, index) => {
      return h(StatusTag, {
        status: row.cycle,
        statusMap: cycleMap.reduce(
          (acc, item) => ({
            ...acc,
            [item.value]: {
              text: item.label,
              type: "info",
            },
          }),
          {}
        ),
      });
    },
  },
  {
    label: "任务类型",
    prop: "type",
    show: true,
    render: (row, column, cellValue, index) => {
      return h(StatusTag, {
        status: row.type,
        statusMap: typeMap.reduce(
          (acc, item) => ({
            ...acc,
            [item.value]: {
              text: item.label,
              type: "primary",
            },
          }),
          {}
        ),
      });
    },
  },
  {
    label: "上次运行",
    prop: "lastTime",
    show: true,
  },
  {
    label: "下次运行",
    prop: "nextTime",
    show: true,
  },
  {
    label: "状态",
    prop: "state",
    show: true,
    render: (row, column, cellValue, index) => {
      return h(StatusTag, {
        status: row.state,
        statusMap: statusMap.reduce(
          (acc, item) => ({
            ...acc,
            [String(item.value)]: {
              text: item.label,
              type: item.value === true ? "success" : "danger",
            },
          }),
          {}
        ),
      });
    },
  },
  {
    label: "操作",
    prop: "action",
    show: true,
    slot: "action",
    fixed: "right",
  },
]);

// 搜索表单数据
const searchFormData = reactive({
  name: "",
});

// 搜索表单配置
const searchFormConfig: FormItemConfig[] = [
  {
    key: "name",
    name: "任务名称",
    type: "input",
    placeholder: "请输入任务名称",
    params: {
      clearable: true,
      style: { width: "200px" },
    },
  },
];

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定删除该计划任务吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      // 调用删除接口
      await deleteChildScheduledTask({ ids: [row.id] });
      ElMessage.success("删除成功");
      getPageData();
    } catch (error) {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  });
};

const getPageData = async () => {
  loading.value = true;

  try {
    // 调用接口获取数据
    const response = await getChildScheduledTaskData({
      search: searchFormData.name,
      pageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
    });

    if (response.code === 200) {
      taskList.value = response.data.list || [];
      pagination.total = response.data.total || 0;
    } else {
      throw new Error(response.message || "获取数据失败");
    }
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error("获取数据失败");
    taskList.value = [];
    pagination.total = 0;
  }

  loading.value = false;
};

onMounted(() => {
  getPageData();
});

const handleSearch = (value: any) => {
  // 更新搜索表单数据
  searchFormData.name = value.name || "";
  pagination.currentPage = 1;
  getPageData();
};

const handleSearchReset = () => {
  // 重置表单数据
  searchFormRef.value?.resetFields();
  searchFormData.name = "";
  pagination.currentPage = 1;
  getPageData();
};

const handlePaginationChange = (page: number) => {
  pagination.currentPage = page;
  getPageData();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1; // 重置到第一页
  getPageData();
};
</script>

<template>
  <!-- 搜索表单 -->
  <el-card shadow="never">
    <div class="search-form-container">
      <DynamicForm
        ref="searchFormRef"
        v-model="searchFormData"
        :form-config="searchFormConfig"
        :gutter="16"
        label-width="80px"
        type="search"
        @search="handleSearch"
        @reset="handleSearchReset"
      />
    </div>
  </el-card>
  <div style="height: 10px"></div>
  <el-card>
    <DynamicTable
      :pagination="pagination"
      :columns="columns"
      :data="taskList"
      :loading="loading"
      @current-page-change="handlePaginationChange"
      @size-change="handleSizeChange"
    >
      <template #action="{ row }">
        <el-button type="danger" size="small" @click="handleDelete(row)">
          删除
        </el-button>
      </template>
    </DynamicTable>
  </el-card>
</template>

<style scoped lang="scss">
// 标签样式
:deep(.el-tag) {
  margin-right: 4px;
  margin-bottom: 2px;
}

// 详情对话框样式
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-select) {
  width: 100%;
}

// 响应式设计
@media (max-width: 768px) {
  .search-form-container {
    flex-direction: column;
  }
}
</style>
